package com.fanghaoran.notes.controller;

import com.alibaba.fastjson.JSON;
import com.fanghaoran.notes.bean.MyResult;
import com.fanghaoran.notes.entity.Cart;
import com.fanghaoran.notes.entity.Item;
import com.fanghaoran.notes.entity.Orders;
import com.fanghaoran.notes.entity.User;
import com.fanghaoran.notes.service.CartService;
import com.fanghaoran.notes.service.OrderService;
import com.fanghaoran.notes.service.ProductService;
import com.fanghaoran.notes.service.impl.CartServiceImpl;
import com.fanghaoran.notes.service.impl.OrderServiceImpl;
import com.fanghaoran.notes.service.impl.ProductServiceImpl;
import com.fanghaoran.notes.util.Constants;
import com.fanghaoran.notes.util.OrderIdUtil;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: win11
 * @Date: 2023/04/23/9:54
 * @Description: 订单controller
 */
@WebServlet("/order")
public class OrderController extends BaseServlet{
    /**
     * service对象
     */
    OrderService orderService=new OrderServiceImpl();
    CartService cartService=new CartServiceImpl();
    ProductService productService=new ProductServiceImpl();

    /**
     * 添加订单以及订单项
     * @param request 请求
     * @param response 响应
     * @throws Exception 异常
     */
    public void addOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取前端传来的cart参数 判断此次提交订单是购物车还是普通购买
        String isCart = request.getParameter("isCart");
        //获取前端传来的sum参数(对于购物车来说是>=1个订单项的价格总和 对于普通购买来说是某一个订单项的价格总和)
        String sum = request.getParameter("sum");
        BigDecimal count = new BigDecimal(sum);
        //获取用户
        User user=(User)request.getSession().getAttribute(Constants.LOGIN_SESSION_PARAM);
        //获取用户id
        Integer uId = user.getUId();
        //生成订单编号
        String oId = OrderIdUtil.createOrderId();
        //生成订单时间
        LocalDateTime oTime = LocalDateTime.now();

        //封装数据
        Orders order = new Orders(oId, uId, count, oTime, Constants.ORDER_UN_PAYED);
        //数据库插入订单数据操作并返回结果给前端
        MyResult result = orderService.addOrder(order);
        if(result.getCode().equals(Constants.SUCCESS)){
            response.getWriter().println(JSON.toJSONString(new MyResult(Constants.SUCCESS,order)));
        }

        //生成订单项
        //如果是购物车提交订单
        if(Integer.parseInt(isCart)==Constants.IS_CART) {
            //将购物车数据转化为订单项数据(插入订单项)
            //先获取该用户的购物车数据
            @SuppressWarnings("unchecked")
            List<Cart> carts=(List<Cart>)cartService.showCart(uId).getData();
            //拿出订单项需要的数据并封装起来传给dao层处理
            for (Cart cart : carts) {
                //商品id(订单项Id)
                int pId = cart.getPId();
                //商品数目及该项总价格
                int num = cart.getNum();
                BigDecimal iCount = cart.getCount();
                //封装数据
                Item item=new Item();
                item.setOId(oId);
                item.setPId(pId);
                item.setINum(num);
                item.setICount(iCount);
                //交给业务层进行插入
                orderService.addItem(item);
            }
            //删除购物车数据
            cartService.removeAllCart(uId);
        }
        //如果是普通购买
        else{
            //获取前端传来的pId num(sum上面已经有了)
            String pId = request.getParameter("pId");
            String num = request.getParameter("num");
            //封装item数据
            Item item=new Item();
            item.setOId(oId);
            item.setPId(Integer.parseInt(pId));
            item.setINum(Integer.parseInt(num));
            item.setICount(count);
            //交给业务层进行插入
            orderService.addItem(item);
        }
    }

    /**
     * 展示订单
     * @param request 请求
     * @param response 响应
     * @throws Exception 异常
     */
    public void showOrder(HttpServletRequest request,HttpServletResponse response) throws Exception {
        //session获取用户
        User user= (User)request.getSession().getAttribute(Constants.LOGIN_SESSION_PARAM);
        //获取用户id
        Integer uId = user.getUId();
        //根据uid查询订单数据 并返回
        response.getWriter().println(JSON.toJSONString(orderService.showOrder(uId)));
    }

    /**
     * 展示订单详情
     * @param request 请求
     * @param response 响应
     * @throws Exception 异常
     */
    public void showOrderDetail(HttpServletRequest request,HttpServletResponse response) throws Exception {
        //接收前端发过来的oId
        String oId = request.getParameter("oId");
        //根据oId以及关联三个表把订单详情要的数据全找出来 放在OrderDetail中 并返回给前端
        response.getWriter().println(JSON.toJSONString(orderService.showOrderDetail(oId)));
    }

    /**
     * 点击确认收货时修改订单状态以及产品的销量库存
     * @param request 请求
     * @param response 响应
     * @throws Exception 异常
     */
    public void modifyStateAndProduct(HttpServletRequest request,HttpServletResponse response) throws Exception {
        //接收前端参数
        String oId = request.getParameter("oId");
        String oState = request.getParameter("oState");
        //业务层处理
        response.getWriter().println(JSON.toJSONString(orderService.modifyState(oId,Integer.parseInt(oState))));
    }

    /**
     * 展示退款信息(用户模块)
     * @param request 请求
     * @param response 响应
     * @throws Exception 异常
     */
    public void showRefund(HttpServletRequest request,HttpServletResponse response) throws Exception {
        //获取前端传来的参数
        String iid = request.getParameter("iid");
        //业务层查询退款信息数据
        response.getWriter().println(JSON.toJSONString(orderService.showRefund(Integer.parseInt(iid))));
    }

    /**
     * 为商家展示退款信息
     * @param request 请求
     * @param response 响应
     * @throws Exception 异常
     */
    public void showRefundForSeller(HttpServletRequest request,HttpServletResponse response) throws Exception {
        //获取商家id
        User user=(User) request.getSession().getAttribute(Constants.LOGIN_SESSION_PARAM);
        Integer uId = user.getUId();
        //业务层查询
        response.getWriter().println(JSON.toJSONString(orderService.showRefundForSeller(uId)));
    }

    /**
     * 添加退款信息
     * @param request 请求
     * @param response 响应
     * @throws SQLException 异常
     * @throws IOException 异常
     */
    public void addRefund(HttpServletRequest request,HttpServletResponse response) throws SQLException, IOException {
        //获取前端参数
        String iid = request.getParameter("iid");
        String reason = request.getParameter("reason");
        String state = request.getParameter("state");
        //获取用户id
        User user=(User) request.getSession().getAttribute(Constants.LOGIN_SESSION_PARAM);
        Integer uId = user.getUId();
        //业务层插入
        response.getWriter().println(JSON.toJSONString(orderService.addRefund(Integer.parseInt(iid),reason,Integer.parseInt(state),uId)));
    }

    /**
     * 修改退款信息的状态
     * @param request 请求
     * @param response 响应
     * @throws SQLException 异常
     * @throws IOException 异常
     */
    public void modifyRefundState(HttpServletRequest request,HttpServletResponse response) throws SQLException, IOException {
        //获取前端参数
        String iid = request.getParameter("iid");
        String state = request.getParameter("state");
        //业务层修改
        response.getWriter().println(JSON.toJSONString(orderService.modifyRefundState(Integer.parseInt(iid),Integer.parseInt(state))));
    }

    //商家模块
    /**
     * 商家查看购买详情
     * @param request 请求
     * @param response 响应
     */
    public void showSellDetail(HttpServletRequest request,HttpServletResponse response) throws Exception {
        //获取商家id
        User user = (User) request.getSession().getAttribute(Constants.LOGIN_SESSION_PARAM);
        if(user!=null) {
            Integer uId = user.getUId();
            //根据商家id去业务层获取数据 并返回
            response.getWriter().println(JSON.toJSONString(orderService.showSellDetail(uId)));
        }
    }
}
